package cn.bdqn.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
public class CodeController {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    //生成验证码
    @GetMapping("/api/getCode")
    public void  getCode(HttpServletResponse response, HttpSession session) throws IOException {
        // 定义图形验证码的长、宽、验证码位数、线性数量
        //还有更多功能自行研究，这里只做简单实现
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(125, 50,4,5);
        stringRedisTemplate.opsForValue().set("code",lineCaptcha.getCode());
        //响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //将生成的验证码图片通过流的方式返回给前端
        ImageIO.write(lineCaptcha.getImage(), "JPEG", outputStream);
    }
}
